const express = require("express");
const app = express();
const port = 3003;

const fs = require("fs");
const md5 = require("md5");
const bodyParser = require("body-parser");
app.use(bodyParser.json());
const jwt = require("jsonwebtoken");

const user = require('./sql/user')
const registerpassword = require('./sql/registerpassword')
const production = require('./sql/production')
const staff = require('./sql/staff')
const admin = require('./sql/admin')

const cors = require('cors');

app.use(cors())
app.use(bodyParser.urlencoded({
    extended: false
}));


//123   md5(123)  Jhi78   1 A向后推10位数 10J 

const passwdCrypt = (req, res, next) => {
    var passwd = req.body.password;
    req.body.passwdCrypted = md5(passwd);
    next();
};

app.post('/ce', (req, res) => {
    console.log('进来了ce')
    console.log(req.body)
    res.send({
        code: '1000',
        info: 'success',
        info2: req.body.user_info
    })
})

app.get("/", (req, res) => res.send("Hello World!"));
app.post("/init", passwdCrypt, (req, res) => {
    res.send("init password is:" + req.body.passwdCrypted);
    // init password is:f5e441058f94f7318dc0【明文密码是123456】
});
const checkToken = function (req, res, next) {
    console.log('我进入校验token识别 这一步了')
    console.log('token')
    console.log(req.query.token)
    // 怎么样都可以传  这只是一种传递方式  能过来让服务器看见token就可以了
    var _token = req.query.token

    //这里要做 更合理的  各种情况的处理
    try {
        // jwt引擎 反推这个秘文  是否是我给你的  是的话 把你秘文变成你的 用户信息 还原
        let verify = jwt.verify(_token, jwt_secret)
        console.log('verify')
        console.log(verify)
        if (verify) {
            console.log('我进入verify里面了')
            req.body.user_info = verify
            console.log('req.body.user._info', req.body.user_info)
            next()
        }


    } catch (error) {
        res.send({
            code: '888',
            info: '你是不是没有我们的权限token乱来啊请重新登陆 '
        })
    }
}

//获取商品数据
app.get('/shop', async (req, res) => {
    production.find({}, (err, data) => {
        if (err) {
            console.log("err", err)
        }
        if (data) {
            res.send({
                code:200,
                data: data
            })
        } else {
            res.send({
                code: 401
            })
        }

    })
})

//搜索商品
app.get('/searchShop', function (req, res) {
    const {
        proName
    } = req.query
    production.find({
        proName: proName
    }, (err, data) => {
        if (err) {
            console.log("err", err)
        }
        if (data) {
            res.send({
                code: '200',
                data: data
            })
        } else {
            res.send({
                code: '400',
                data: "没有查询到数据"
            })
        }
    })
})

//删除商品数据
app.get("/deleteShop", function (req, res, next) {
    production.deleteOne({
        '_id': req.query[0]
    }, (err, data) => {
        if (err) {
            console.log("err", err)
        }
        if (data) {
            res.send({
                code: 200,
                data: data
            });
        }else{
            res.send({
                code: 401,
            });
        }
    })
});

//添加商品数据
app.post("/addShop", function (req, res, next) {
    const obj = req.body;
    // obj.stock = Number(obj.stock);
    // obj.price = Number(obj.price);
    // obj.discount = obj.discount - 0;
    // obj.score = obj.score * 1;
    console.log(obj);
    production.insertMany(obj.params, (err, data) => {
        if (err) {
            console.log('err',err)
        }
        if (data) {
            res.send({
                code: 200,
                data:data
            });
        }
        else{
            res.send({
                code: 401
            });
        }
    })
});

//获取用户数据
app.get('/user', async (req, res) => {
    user.find({}, (err, data) => {
        if (err) {
           console.log('err',err)
        }
        if(data){
            res.send({
                code:200,
                data: data
            })
        }
        else{
            res.send({
                code:401,
            })
        }
    })
})

//搜索用户
app.get('/searchUser', function (req, res) {
    const {
        userName
    } = req.query
    user.find({
        username: userName
    }, (err, data) => {
        if (err) {
            console.log('err',err)
        }
        if (data) {
            res.send({
                code: '200',
                data: data
            })
        } else {
            res.send({
                code: '401',
                data: "没有查询到用户"
            })
        }
    })
})

//删除用户数据
app.get("/deleteUser", function (req, res, next) {
    user.deleteOne({
        '_id': req.query[0]
    }, (err, data) => {
        if (err) {
            console.log('err',err)
        }
        if(data){
            res.send({
                code: 200,
                data: data
            });
        }else{
            res.send({
                code:401,
            })
        }
        
    })
});

//添加用户数据
app.post("/addUser", function (req, res, next) {
    const obj = req.body;
    console.log(obj);
    user.insertMany(obj.params, (err, data) => {
        if (err) {
            console.log('err',err)
        }
        if (data) {
            res.send({
                code: 200,
                data:data,
            });
        }else{
            res.send({
                code:401,
            });
        }
    })
});

//修改员工
app.post("/updateUser",function(req,res){
    const obj = req.body
    user.findByIdAndUpdate(obj.params._id,obj.params,(err, data) => {
        if (err) {
            console.log('err',err)
        }
        console.log(data)
        if (data) {
            res.send({
                code: 200,
                data:data,
            });
        }else{
            res.send({
                code:401,
            });
        }
    })

})

//获取员工数据
app.get('/staff', async (req, res) => {
    staff.find({}, (err, data) => {
        if (err) {
           console.log("err",err)
        }
        if(data){
            res.send({
                code:200,
                data: data
            })
        }else{
            res.send({
                code:401,
            })
        }
        
    })
})

//搜索员工
app.get('/searchStaff', function (req, res) {
    const {
        staffName
    } = req.query
    staff.find({
        username: staffName
    }, (err, data) => {
        if (err) {
            console.log('err',err)
        }
        if (data) {
            res.send({
                code: '200',
                data: data
            })
        } else {
            res.send({
                code: '401',
                data: "没有查询到用户"
            })
        }
    })
})

//删除员工数据
app.get("/deleteStaff", function (req, res, next) {
    staff.deleteOne({
        '_id': req.query[0]
    }, (err, data) => {
        if (err) {
            console.log(err)
        }
        res.send({
            code: 200,
            data: data
        });
    })
});

//添加员工数据
app.post("/addStaff", function (req, res, next) {
    const obj = req.body;
    console.log(obj);
    user.insertMany(obj.params, (err, data) => {
        if (err) {
            console.log('err',err)
        }
        if (data) {
            res.send({
                code: 200,
                data:data
            });
        }else{
            res.send({
                code: 401
            });
        }
    })
});

//注册页面
app.get('/register',(req,res,next)=>{
    const {username,password} = req.query
    
})



//登录权限
app.post('/login', (req, res, next) => {
    const {
        username,
        password
    } = req.body.params
    user.findOne({
        username,
        password
    }, (err, data) => {
        if (err) {
            console.log('err',err)
        }
        if (data) {
            if (username !== '霸道总裁' && username !== '戴学腾') {
                console.log('普通员工用户进来了 给个稍许的权限吧')
                res.send({
                    id: 1,
                    username: username,
                    password: password,
                    operation: false,
                    addShop: false,
                    updateShop: false,
                    deleteShop: false,
                    shop: true,
                    user: false,
                    staff: false,
                    Nuclearmissile: false,
                    token: 'abcdefghijklmnopqrstuvwxyz',
                    rights: [{
                        children: [{
                            path: '/home/shouye',
                        }, {
                            path: '/home/shop',
                        }]
                    }, ]
                })
            } else if (username === '戴学腾' && password === '123456') {
                console.log('戴学腾进来了 给个稍许的权限吧')
                res.send({
                    id: 1,
                    username: username,
                    password: password,
                    operation: true,
                    addShop: true,
                    updateShop: true,
                    deleteShop: true,
                    shop: true,
                    user: true,
                    staff: false,
                    Nuclearmissile: false,
                    token: 'abcdefghijklmnopqrstuvwxyz',
                    rights: [{
                        children: [{
                            path: '/home/shouye',
                        }, {
                            path: '/home/shop',
                        }, {
                            path: '/home/user',
                        }, {
                            path: '/home/addshop',
                        }, {
                            path: '/home/adduser',
                        }]
                    }]
                })
            } else if (username === '霸道总裁' && password === '123456') {
                console.log('霸道总裁进入后端路由了')
                res.send({
                    id: 2,
                    username: username,
                    password: password,
                    operation: true,
                    addShop: true,
                    updateShop: true,
                    deleteShop: true,
                    shop: true,
                    user: true,
                    staff: true,
                    Nuclearmissile: true,
                    token: 'abcdefghijklmnopqrstuvwxyz'.split('').reverse().join(''),
                    rights: [{
                        children: [{
                            path: '/home/shouye',
                        }, {
                            path: '/home/shop',
                        }, {
                            path: '/home/user',
                        }, {
                            path: '/home/staff',
                        }, {
                            path: '/home/addshop',
                        }, {
                            path: '/home/adduser',
                        }, {
                            path: '/home/addstaff',
                        }, {
                            path: '/home/updateshop',
                        }, {
                            path: '/home/updateuser',
                        }]
                    }, ]
                })
            }
        } else {
            res.send({
                code: 401,
                msg: "你可能不是我们的内部员工"
            })
        }

    })

})

app.listen(port, () => console.log(`Server is running at http://127.0.0.1:${port}!`));